<template>
  <div class="app-container">

    <!--搜索条件-->
    <div id="foldDiv">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="编码" prop="stockCode">
          <el-input v-model="queryParams.stockCode" @clear="handleQuery" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="名称" prop="stockName">
          <el-input v-model="queryParams.stockName" @clear="handleQuery" @blur="handleQuery" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="行业" prop="industry">
          <el-input v-model="queryParams.industry" @clear="handleQuery" @blur="handleQuery" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="交易所" prop="stockExchange">
          <el-select v-model="queryParams.stockExchange" placeholder="请选择" @change="getList" clearable>
            <el-option v-for="dict in dict.type.stock_exchange" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>&nbsp;
          <el-link type="primary" href="http://www.sse.com.cn/assortment/stock/list/share" target="_blank">上交所下载
          </el-link>&nbsp;
          <el-link type="success" href="http://www.szse.cn/market/product/stock/list/index.html" target="_blank">深交所下载
          </el-link>
          <el-button style="margin-left: 5px" type="danger" size="mini" @click="updateAllStockInfoFromAPI">更新所有股票
          </el-button>
          <el-button style="margin-left: 5px" type="primary" size="mini" @click="testUpdateAllStockAPI">测试接口
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--K线图-->
    <div v-if="isShowKLine">
      <template v-for="(item, index) in stockCodeKLine">
        <el-card style="margin-top:20px">
          <div :id="'d'+item.split('_')[0]" style="width: 100%;height: 600px"></div>
        </el-card>
      </template>
    </div>

    <!--我的K线图-->
    <div v-if="isShowMyKLine">
      <template v-for="(item) in stockCodeKLine">
        <el-card style="margin-top:20px">
          <div :id="'d'+item.split('_')[0]" style="width: 100%;height: 600px"></div>
        </el-card>
      </template>
    </div>

    <!--操作按钮-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleClearStockData">清空股票
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-pie-chart" size="mini" @click="handleGenerateKLine">查看K线
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-sunny" size="mini" @click="handleGenerateMyKLine">我的K线
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-plus" size="mini" @click="handleBatchAddMyAttention">批量关注
        </el-button>
      </el-col>
      <el-col :span="1.5">
        left:{{ left }},top:{{ top }},bottom:{{ bottom }}
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--表格列表-->
    <el-table id="tableDiv" :height="tableHeight" v-loading="loading" :data="stockList" border ref="tableRef"
              :row-class-name="tableRowClassName"
              :cell-class-name="tableCellClassName"
              highlight-current-row
              @cell-click="handleCellClick"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="股票code" width="102px" sortable="custom" align="center" prop="stockCode"/>
      <el-table-column prop="stockName" label="股票名称">
        <template slot-scope="scope">
          <el-tag :type="'primary'" disable-transitions>{{ scope.row.stockName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="当前价" sortable="custom" align="center" prop="currentPrice"/>
      <el-table-column label="涨跌幅" sortable="custom" :formatter="formatter" align="center" prop="priceRiseRange"/>
      <el-table-column label="所属交易所" width="100px" align="center" prop="stockExchange"/>
      <el-table-column label="上市日期" width="100px" sortable="custom" align="center" prop="listingDate"/>
      <el-table-column label="股票类型" align="center" prop="stockType"/>
      <el-table-column label="总股本" align="center" prop="marketCapital"/>
      <el-table-column label="流通股" align="center" prop="negotiableCapital"/>
      <el-table-column label="所属行业" align="center" prop="industry"/>
      <el-table-column label="操作" width="240px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleAddMyAttentionToDefault(scope.row)">默关
          </el-button>
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleAddMyAttention(scope.row)">加注
          </el-button>
          <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" @pagination="getList" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"/>

    <!-- 新增修改弹窗组件-->
    <addOrUpdate ref="addOrUpdateDialog" :addOrUpdateParam="addOrUpdateParam" @getList="getList"/>

    <!-- 添加到我的关注-->
    <AddMyAttention v-if="addMyAttentionParam.open" ref="addMyAttentionDialog" :addOrUpdateParam="addMyAttentionParam"/>

    <!-- 导入组件 -->
    <importFile ref="importFileDialog" :upload="uploadParam" @success="getList"/>

    <!-- 批量添加关注对话框 -->
    <el-dialog :title="title" :visible.sync="batchAttentionOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分组" prop="groupId">
          <el-select :popper-append-to-body="false" popper-class="el-select-popper" v-model="form.groupId"
                     clearable>
            <el-option v-for="item in attentionOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 滑动到页面底部会看见-->
    <el-backtop>返回</el-backtop>

  </div>
</template>

<script>
import {listStock, delStock, clearStockData, updateAllStockInfoFromAPI, testUpdateAllStockAPI} from '@/api/eye/stock'
import {getToken} from '@/utils/auth'
import {renderKLine} from '@/api/eye/kline'
import {initDragonKLine} from '@/api/eye/myKLine.js'
import {getHistoryPriceByStockCode} from '@/api/eye/stockPrice'
import {listStockGroupOption} from '@/api/eye/stockGroup'
import ImportFile from '../components/ImportFile'
import AddOrUpdate from './addOrUpdate.vue'
import AddMyAttention from '../myAttention/addOrUpdate'
import {addMyAttention as addMyAttentionToDefault,batchInsertMyAttention} from '@/api/eye/myAttention'
import Vue from 'vue'
import ElementResizeDetectorMaker from 'element-resize-detector'

Vue.prototype.$erd = ElementResizeDetectorMaker()

export default {
  name: 'Stock',
  dicts: ['stock_exchange'],
  components: {AddOrUpdate, AddMyAttention, ImportFile},
  data() {
    return {
      stockCodeKLine: [],
      stockCodeList: [],
      attentionOptions: [],
      batchAttentionOpen: false,
      left: 0,
      top: 0,
      bottom: 0,
      addOrUpdateParam: {
        open: false // 是否显示弹出层
      },
      addMyAttentionParam: {
        open: false // 是否显示弹出层
      },
      tableHeight: '500',
      // 上传参数
      uploadParam: {},
      // K线图是否显示
      isShowKLine: false,
      // 展示我的K线
      isShowMyKLine: false,
      // 遮罩层
      loading: true,
      // 选中IDS
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 股票基础信息表格数据
      stockList: [],
      // 弹出层标题
      title: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        stockCode: null,
        stockName: null,
        industry: null,
        stockExchange: null
      },
      // 导入参数
      upload: {
        // 弹出层标题（导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: 'Bearer ' + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/eye/stock/importData'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.listStockGroupOption()
    this.getList()
  },
  mounted() {
    this.getTableMaxHeight()
    let _this = this
    window.onresize = function () {
      console.log('onresize 股票')
      //页面改变重新自适应高度
      _this.getTableMaxHeight()
    }
    this.$erd.listenTo(document.getElementById('foldDiv'), (element) => {
      _this.getTableMaxHeight()
    })
  },
  methods: {
    //获取容器当前高度，重设表格的最大高度
    getTableMaxHeight() {
      this.$nextTick(function () {
        let t = document.querySelector('#tableDiv')
        console.log('股票信息 重置高度')
        // 在别的页面缩放此值为null
        if (t == null) return
        this.tableHeight = window.innerHeight - t.getBoundingClientRect().top - 80
      })
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 === 0) {
        return 'warning-row'
      } else {
        return ''
      }
    },
    tableCellClassName({row, column, rowIndex, columnIndex}) {
      if (column.label === '涨跌幅') {
        if (row.priceRiseRange != null) {
          if (row.priceRiseRange > 0) {
            return 'price_rise'
          } else {
            return 'price_down'
          }
        }
      }
    },
    formatter(row, column) {
      if (row.priceRiseRange != null) {
        return (row.priceRiseRange * 100).toFixed(2) + '%'
      }
    },
    /** 查询股票基础信息列表 */
    getList() {
      this.loading = true
      listStock(this.queryParams).then(response => {
        this.stockList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取关注分组 */
    listStockGroupOption() {
      listStockGroupOption().then(response => {
        response.data.forEach((item) => {
          let o = {}
          o.value = item.id
          o.label = item.name
          o.raw = {listClass: item.classStyle}
          this.attentionOptions.push(o)
        })
      })
    },
    // 表单重置
    reset() {
      this.form = {
        stockCode: null,
        stockName: null,
        industry: null,
        stockExchange: null
      }
      this.resetForm('form')
    },
    /**
     * 从第三方接口更新所有的股票信息
     */
    updateAllStockInfoFromAPI() {
      this.loading = true
      updateAllStockInfoFromAPI().then(() => {
        this.loading = false
        this.$modal.msgSuccess('更新完成!')
      })
    },
    testUpdateAllStockAPI() {
      this.loading = true
      testUpdateAllStockAPI().then((res) => {
        this.loading = false
        let data = '';
        res.data.forEach(item => {
          data += '<strong>' + JSON.stringify(item) + '</strong></br>'
        })
        this.$alert(data, '返回数据', {
          dangerouslyUseHTMLString: true
        });
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.isShowKLine = false
      this.isShowMyKLine = false
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.isShowMyKLine = false
      this.resetForm('queryForm')
      this.handleQuery()
    }
    ,
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.stockCodeList = selection.map(item => item.stockCode)
      this.stockCodeKLine = selection.map(item => item.stockCode + '_' + item.stockName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
    ,
    /** 新增按钮操作 */
    handleAdd() {
      console.log('调用子组件的添加弹窗')
      this.$refs.addOrUpdateDialog.handleAdd()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.addOrUpdateDialog.handleAdd(row.id)
    },
    //选中行,查看选中K线图
    handleCellClick(row, column, cell, event) {
      console.log('单击单元格')
      if (column.label === '股票code' || column.label === '股票名称' || column.label === '当前价' || column.label === '涨跌幅') {
        //点击前n列触发
        console.log('选中股票code:' + row.stockCode)
        this.isShowKLine = true
        getHistoryPriceByStockCode(row.stockCode).then(response => {
          renderKLine('d' + row.stockCode, row.stockName, response.data)
        })
      }
    },
    // 排序
    handleSortChange(column, prop, order) {
      console.log('排序')
      console.log(prop)
      console.log(order)
      // 排序字段
      let sortColumn = column.prop
      // 升序还是降序
      let sortOrder = column.order
      this.queryParams.orderByColumn = sortColumn
      if (sortOrder === 'ascending') {
        this.queryParams.isAsc = 'asc'
      } else {
        this.queryParams.isAsc = 'desc'
      }
      this.getList()
    },
    /** 添加到我的关注 */
    handleAddMyAttention(row) {
      console.log('调用子组件的添加弹窗')
      this.addMyAttentionParam.open = true
      this.form = {stockCode: row.stockCode, stockName: row.stockName, groupId: '1', stockExchange: 'fund'}
      this.$nextTick(() => {
        this.$refs.addMyAttentionDialog.handleAddOrUpdate(this.form)
      })
    },
    /** 添加到我的关注的默认分组 */
    handleAddMyAttentionToDefault(row) {
      console.log('添加到我的关注的默认分组')
      this.form = {stockCode: row.stockCode, stockName: row.stockName, groupId: '1'}
      addMyAttentionToDefault(this.form).then(() => {
        this.$modal.msgSuccess('已加入默认分组!')
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除股票基础？').then(function () {
        return delStock(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      console.log('导入')
      this.uploadParam = {
        open: true,             // 是否显示
        title: '导入文件',       // 弹出层标题（导入）
        isUploading: false,    // 是否禁用上传
        updateSupport: 1,      // 是否更新已经存在的用户数据
        headers: {Authorization: 'Bearer ' + getToken()}, // 设置上传的请求头部
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/eye/stock/importData',
        // 模板下载路径
        templateUrl: 'eye/stock/importTemplate',
        // 模板下载名称
        templateName: 'download'
      }
      console.log(this.uploadParam)
    },
    /** 清空数据 */
    handleClearStockData: function () {
      console.log('清空数据')
      this.$modal.confirm('是否确认要清空数据?').then(function () {
        clearStockData()
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('清空数据成功')
      }).catch(() => {
      })
    },
    /** 生成K线图 */
    handleGenerateKLine() {
      this.isShowKLine = true
      this.stockCodeKLine.forEach(item => {
        let code = item.split('_')[0]
        getHistoryPriceByStockCode(code).then(response => {
          renderKLine('d' + code, item, response.data, 1)
        })
      })
    },
    /** 生成我的K线图 */
    handleGenerateMyKLine() {
      this.isShowMyKLine = true
      this.stockCodeKLine.forEach(item => {
        let code = item.split('_')[0]
        getHistoryPriceByStockCode(code).then(response => {
          initDragonKLine('d' + code, item, response.data.date, response.data.price)
        })
      })
    },
    /** 批量添加我的关注 */
    handleBatchAddMyAttention() {
      this.batchAttentionOpen = true
      this.title = '批量关注'
    },
    /** 提交按钮 */
    submitForm() {
      this.form.stockCodeList = this.stockCodeList
      batchInsertMyAttention(this.form).then(response => {
        this.batchAttentionOpen = false
        this.$modal.msgSuccess("新增成功");
      });
    },
    // 取消按钮
    cancel() {
      this.batchAttentionOpen = false;
    },
  }
}
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.price_rise {
  color: red !important;
}

.price_down {
  color: green !important;
}
</style>

<style scoped>
::v-deep .el-table .el-table__body tr td:hover {
  background-color: #F56C6C !important;
  cursor: pointer;
}

a:hover {
  background-color: purple;
}

.el-card.is-always-shadow {
  box-shadow: 0 12px 9px red;
}
</style>

